import 'package:flutter/material.dart';
import '../../models/order_list_model.dart';
import '../../l10n/app_localizations.dart';
import 'package:gif/gif.dart';
import '../../manger/cached_image_widget.dart';
import '../../models/adress_info_model.dart';

typedef OnPaymentSelected = void Function(PayListModel payListModel);

class PaymentView extends StatefulWidget {
  final List<PayListModel> payList;
  final OnPaymentSelected? onSelected;
  final List<CardInfo> cardList; // 快捷卡列表
  final ValueChanged<String> onCardSelected;
  final VoidCallback? onShowAuthTips;

  const PaymentView({
    super.key,
    required this.payList,
    this.onSelected,
    required this.onCardSelected,
    this.cardList = const [],
    this.onShowAuthTips, // 初始化快捷卡列表，默认为空列表
  });

  @override
  State<PaymentView> createState() => _PaymentViewState();
}

class _PaymentViewState extends State<PaymentView> {
  bool isUnfold = false;
  int? selectedIndex;

  @override
  void initState() {
    super.initState();
    selectedIndex = 0;
  }

  @override
  void didUpdateWidget(PaymentView oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 如果 cardList 改变，重新更新 selectedIndex
    if (widget.cardList != oldWidget.cardList && widget.cardList.isNotEmpty) {
      setState(() {
        selectedIndex = widget.cardList.length;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    final isFoldable = widget.payList.length > 2;
    final visibleList =
        isUnfold ? widget.payList : widget.payList.take(2).toList();

    return Padding(
      padding: const EdgeInsets.only(left: 15, right: 15, top: 15),
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xFFEAEAFF),
          borderRadius: BorderRadius.circular(15),
        ),
        child: Column(
          children: [
            // Header: Number + Title
            Padding(
              padding: const EdgeInsets.only(top: 10, left: 15, bottom: 10),
              child: Row(
                children: [
                  Container(
                    width: 18,
                    height: 18,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: const Color(0xFF5D5FEE),
                      borderRadius: BorderRadius.circular(9),
                    ),
                    child: const Text(
                      '3',
                      style: TextStyle(color: Colors.white, fontSize: 13),
                    ),
                  ),
                  const SizedBox(width: 7),
                  Text(
                    AppLocalizations.of(context)!.paymentmethod,
                    style: const TextStyle(fontSize: 14, color: Colors.black),
                  ),
                ],
              ),
            ),

            // bgView 白底区域
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(15),
              ),
              child: Column(
                children: [
                  if (widget.cardList.isNotEmpty)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 13),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              AppLocalizations.of(context)!.jisuzhifu,
                              style: TextStyle(fontSize: 14, color: Color(0xFF000000)),
                            ),
                            Text(
                              AppLocalizations.of(context)!.morepayment2,
                              style: const TextStyle(
                                  fontSize: 12,
                                  color: Color(0xFF666666),
                                  fontWeight: FontWeight.w400),
                            ),                            
                          ]
                        ),
              
                        ListView.builder(
                          shrinkWrap: true,
                          physics: NeverScrollableScrollPhysics(),
                          padding: EdgeInsets.zero, // 添加这行
                          itemCount: widget.cardList.length,
                          itemBuilder: (context, index) {
                            final card = widget.cardList[index];
                            return CardCell(
                              cardNo: card.cardNo,
                              isSelected: selectedIndex == index,
                              onTap: () {
                                setState(() {
                                  selectedIndex = index;
                                });
                                widget.onCardSelected(card.paymentConsentId);        
                              },
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                  // 分组头
                  Container(
                    padding: const EdgeInsets.symmetric(
                    horizontal: 15, vertical: 13),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          AppLocalizations.of(context)!.putongzhifu,
                          style: TextStyle(fontSize: 14, color: Color(0xFF000000)),
                        ),
                        if (isChineseLocale())
                        Text(
                          AppLocalizations.of(context)!.morepayment,
                          style: const TextStyle(
                              fontSize: 12,
                              color: Color(0xFF666666),
                              fontWeight: FontWeight.w400),
                        ),
                      ],
                    ),
                  ),
                  // 支付方式列表
                ...List.generate(visibleList.length, (index) {
                  final model = visibleList[index];
                  final realIndex = widget.cardList.isNotEmpty ? index + widget.cardList.length : index;
                  final isSelected = realIndex == selectedIndex;
        
                  return Column(
                      children: [
                        PaymentItemWidget(
                          onShowAuthTips: () {
                            widget.onShowAuthTips?.call();
                          },
                          model: model,
                          isSelected: isSelected,
                          onTap: () {
                            setState(() {
                              selectedIndex = realIndex;
                            });
                            widget.onSelected?.call(widget.payList[index]);
                          },
                        ),
                        if (index != visibleList.length - 1)
                          const Divider(
                            color: Color(0xFFF6F6F6),
                            height: 1,
                            thickness: 1,
                            indent: 15,
                            endIndent: 15,
                          ),
                      ],
                    );
                  }),

                  // 展开按钮
                  if (isFoldable)
                    TextButton.icon(
                      onPressed: () {
                        setState(() {
                          if (isUnfold && selectedIndex != null && selectedIndex != 0) {             
                            if (widget.cardList.isNotEmpty) {
                              final selectedItem = widget.payList[selectedIndex! - widget.cardList.length];
                              widget.payList.removeAt(selectedIndex!);
                              widget.payList.insert(0, selectedItem);
                              selectedIndex = widget.cardList.length;
                              widget.onSelected?.call(selectedItem);        
                            } else {
                              final selectedItem = widget.payList[selectedIndex!];
                              widget.payList.removeAt(selectedIndex!);
                              widget.payList.insert(0, selectedItem);
                              selectedIndex = 0;
                              widget.onSelected?.call(selectedItem);        
                            }      
                          }
                          isUnfold = !isUnfold;
                        });
                      },
                      icon: isUnfold
                          ? Image.asset(
                              'assets/images/收起.png',
                              width: 16,
                              height: 16,
                            )
                          : Gif(
                              fps: isChineseLocale() ? 10 : 50,
                              autostart: Autostart.loop,
                              image:
                                AssetImage(isChineseLocale() ? 'assets/images/buioesase.gif' : 'assets/images/buioesaseen.gif'),
                              width: 102,
                              height: 37,
                              fit: BoxFit.cover,
                            ),
                      label: isUnfold
                          ? Text(
                              AppLocalizations.of(context)!.shrink,
                              style: const TextStyle(color: Colors.blue),
                            )
                          : const Text(""),
                    ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class PaymentItemWidget extends StatelessWidget {
  final PayListModel model;
  final bool isSelected;
  final VoidCallback onTap;
  final VoidCallback onShowAuthTips;

  const PaymentItemWidget({
    super.key,
    required this.model,
    required this.isSelected,
    required this.onTap,
    required this.onShowAuthTips,
  });

  @override
  Widget build(BuildContext context) {
    // Determine if the auth tips view should be shown
    bool showAuthTips = model.shopPaymentId == 56 && isSelected;

    return GestureDetector(
      onTap: model.status != 2 ? onTap : null,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 15),
        decoration: BoxDecoration(
          color: Colors.transparent, // Ensure background is transparent
        ),
        child: Row(
          children: [
            // Icon image
            Container(
              width: 80,
              height: 40,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  CachedImage(
                    width: 80,
                    height: 40,
                    imageUrl: model.pic,
                    fit: BoxFit.cover,
                    placeholderPath: 'assets/images/placeholderImage.png',
                  ),
                  if (model.status == 2)
                  Container(
                    width: double.infinity,
                    height: double.infinity,
                    color: Colors.white.withValues(alpha: 0.6), // 半透明白色蒙层
                  ),
                  // 当model.status == 2时显示维护图片
                  if (model.status == 2)
                    Image.asset(
                      'assets/images/weihu' + (getLanguageCode()) + '.png',
                      width: 50,
                      height: 50,
                    ),
                ],
              ),
            ),
            const SizedBox(width: 10),
            // Title and description
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Title
                  Row(
                    children: [
                      Text(
                        model.name,
                        style: const TextStyle(fontSize: 15),
                      ),
                      if (model.shopPaymentId == 56)
                        GestureDetector(
                          onTap: onShowAuthTips,
                          child: Padding(
                            padding: const EdgeInsets.only(left: 5),
                            child: Image.asset(
                              'assets/images/howinfo.png',
                              width: 16,
                              height: 16,
                            ),
                          ),
                        ),
                    ],
                  ),
                  // Description (tips)
                  if (model.tips.isNotEmpty)
                    Padding(
                      padding: const EdgeInsets.only(top: 2),
                      child: Text(
                        model.tips,
                        style: const TextStyle(
                          fontSize: 12,
                          height: 1.2,
                          color: Color(0xFF666666),
                        ),
                      ),
                    ),
                  // Auth Tips View (conditionally visible)
                  if (showAuthTips)
                    GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: onShowAuthTips,
                      child: Padding(
                        padding: const EdgeInsets.only(top: 8),
                        child: Container(
                          padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                          decoration: BoxDecoration(
                            color: Color(0xFFF3F3FF),
                            borderRadius: BorderRadius.circular(5),
                          ),
                          child: Text(
                            '如何认证？查看详细步骤与好处 >',
                            style: TextStyle(
                              fontSize: 12,
                              color: Color(0xFF5D5FEE),
                            ),
                          ),
                        ),
                      ),
                    ),
                ],
              ),
            ),
            // Selection icon
            if (model.status != 2)
            Image.asset(
              isSelected
                  ? 'assets/images/login_select2.png'
                  : 'assets/images/login_unselect2.png',
              width: 20,
              height: 20,
            ),
          ],
        ),
      ),
    );
  }
}


class CardCell extends StatelessWidget {
  final String cardNo;   // 快捷卡号
  final bool isSelected;
  final VoidCallback onTap;

  const CardCell({
    Key? key,
    required this.cardNo,
    required this.isSelected,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 20),
        decoration: BoxDecoration(
          color: Colors.transparent,
          border: Border(bottom: BorderSide(color: Color(0xFFF6F6F6), width: 1)),
        ),
        child: Row(
          children: [
            Image.asset(
              'assets/images/卡密.png', // 替换为你的图标路径
              width: 50,
              height: 32,
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Text(
                cardNo,
                style: const TextStyle(fontSize: 15, color: Color(0xFF666666)),
              ),
            ),
            Image.asset(
              isSelected
                  ? 'assets/images/login_select.png' // 替换为选中状态图标路径
                  : 'assets/images/login_unselect2.png', // 替换为未选中状态图标路径
              width: 20,
              height: 20,
            ),
          ],
        ),
      ),
    );
  }
}

